import {
    reqLogin
} from "../../request/api"

//初始值
const initState = {
    user: {
        phone: "",
        password: "",
    },
    info:sessionStorage.getItem("user")?JSON.parse(sessionStorage.getItem("user")):{}
}

//actionTypes
const types = {
    CHANGE_USER: "LOGIN_CHANGE_USER",
    CHANGE_INFO:"LOGIN_CHNAGE_INFO"
}

//reducer 修改数据
const reducer = (state = initState, action) => {
    switch (action.type) {
        case types.CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        case types.CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }
        default:
            return state;
    }
}

//actionCreators组件派发的动作
export const actions = {
    changeUser: (key, value) => ({
        type: types.CHANGE_USER,
        key,
        value
    }),
    changeInfo:(info)=>{
        if(info.token){
            sessionStorage.setItem("user",JSON.stringify(info))
        }else{
            sessionStorage.removeItem("user")
        }
        return {type:types.CHANGE_INFO,info}
    },
    reqLogin: (history) => (dispatch, getState) => {
        let {user} = getState().login
        console.log(user);
        reqLogin(user).then(res=>{
            if(res.data.code===200){
                dispatch(actions.changeInfo(res.data.list))
                history.push("/index/home")
            }
        })
    }
}

//selectors导出数据
export const getUser = state => state.login.user

export default reducer;